package com.imrookie.gendoc.db.service.impl;

import com.imrookie.gendoc.db.model.Column;
import com.imrookie.gendoc.db.model.Table;
import com.imrookie.gendoc.db.service.DBGenService;
import com.imrookie.gendoc.db.service.DBService;
import freemarker.core.ParseException;
import freemarker.template.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author wangjiyu@imdada.cn 2019/8/9
 */
@Service
public class DBGenServiceImpl implements DBGenService {
    @Autowired
    DBService dbService;
    /**
     * 生成文档
     *
     * @param filePath
     * @param tableIds
     */
    @Override
    public void genWord(String filePath, String... tableIds) throws Exception {

        List<Table> tableList = dbService.getTableList();//库中所有的表

        List<Table> checkTableList = new LinkedList<Table>();//待导出表

        if (tableIds == null || tableIds.length == 0) {
            checkTableList = tableList;
        } else {
            Map<String, String> map = new HashMap<String, String>();
            for (String one : tableIds){
                map.put(one, "1");
            }
            for (Table table : tableList){
                if (map.containsKey(table.getId())){//存在该表,则放入checkTableList
                    checkTableList.add(table);
                }
            }
        }

        //遍历checkTableList,查询各个表的字段信息
        for (Table table : checkTableList){
            table.setColumnList(dbService.getColumsListByTableName(table.getId()));
            table.setIndexWrapList(dbService.getIndexWrapListByTableName(table.getId()));
        }

        //格式化
        for (Table table : checkTableList){
            for (Column col : table.getColumnList()){
                col.setNotNull("1".equals(col.getNotNull()) ? "是" : "否");
            }
        }

        //配置
        Configuration configuration = new Configuration();
        configuration.setClassForTemplateLoading(DBGenServiceImpl.class, "/");//注意路径以斜杠'/'开头

        //获取模板文件
        Template template = configuration.getTemplate("DB_DOC.ftl", "UTF-8");//, "UTF-8"

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("tableList", checkTableList);

        File file = new File(filePath);
        if (file.exists()) {
            file.createNewFile();
        }
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));
        template.process(map, bufferedWriter);//写入
    }
}
